/*
 * @Author: chendeji
 * @Date: 2021-11-16 19:41:09
 * @LastEditTime: 2021-11-16 20:00:55
 * @Description: 
 * @FilePath: \copy_gsy_github_app_flutter\lib\db\provider\dynamic\dynamic_db_provider.dart
 * 联系方式：
 * wx: melody_2009
 * qq: 7815171323 
 */

import 'package:copy_gsy_github_app_flutter/common/model/Event.dart';
import 'package:copy_gsy_github_app_flutter/db/sql_provider.dart';
import 'package:copy_gsy_github_app_flutter/utils/code_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:sqflite/sqlite_api.dart';

class DynamicDbProvider extends DBProvider {
  static const NAME = 'Dynamic';
  static const COLUMN_ID = '_id';
  static const COLUMN_DATA = 'data';

  int? id;
  String? data;

  DynamicDbProvider();

  Map<String, dynamic> toMap(String eventMapString) {
    Map<String, dynamic> map = {COLUMN_DATA: eventMapString};
    if (id != null) {
      map[COLUMN_ID] = id;
    }
    return map;
  }

  DynamicDbProvider.fromMap(Map map) {
    id = map[COLUMN_ID];
    data = map[COLUMN_DATA];
  }

  @override
  sqlCreateTable() {
    return tableBaseString(NAME, COLUMN_ID) +
        '''
        $COLUMN_DATA text not null)
      ''';
  }

  @override
  tableName() {
    return NAME;
  }

  Future insert(String dynamicMapString) async {
    Database db = await getDataBase();
    db.execute("delete from $NAME");
    return await db.insert(NAME, toMap(dynamicMapString));
  }

  Future<List<Event>> getDynamic() async {
    Database db = await getDataBase();
    List<Map> maps = await db.query(NAME, columns: [COLUMN_ID, COLUMN_DATA]);
    List<Event> list = [];
    if (maps.length > 0) {
      DynamicDbProvider provider = DynamicDbProvider.fromMap(maps.first);
      List<dynamic> eventMap =
          await compute(CodeUtils.decodeListResult, provider.data);
      if (eventMap.length > 0) {
        for (var item in eventMap) {
          list.add(Event.fromJson(item));
        }
      }
    }
    return list;
  }
}
